package cn.sycoder.controller;

import cn.sycoder.constant.Const;
import cn.sycoder.dto.ProductAlarmDto;
import cn.sycoder.dto.ProductDto;
import cn.sycoder.entity.Product;
import cn.sycoder.entity.Role;
import cn.sycoder.exception.BusinessException;
import cn.sycoder.mapper.ProductMapper;
import cn.sycoder.resp.Code;
import cn.sycoder.service.IProductService;
import cn.sycoder.utils.JwtUtil;
import cn.sycoder.vo.ProductVo;
import cn.sycoder.vo.RoleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨润发
 * @since 2024-10-25
 */
@RestController
@RequestMapping("/api/Product")
@Api(tags = "库存管理")
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ProductController {

    @Autowired
    IProductService service;

    @Autowired
    ProductMapper mapper;

    @PostMapping("/list")
    @ApiOperation(value = "库存管理-获取库存信息列表")
    public Map<String, Object> productList(@RequestParam(defaultValue = "1") int page,
                                           @RequestParam(defaultValue = "10") int limit,
                                           @RequestParam(value = "name", required = false) String name,
                                           @RequestParam(value = "code", required = false) String code) {
        // 创建返回结果
        Map<String, Object> response = new HashMap<>();

        // 创建分页查询
        Page<Product> objectPage = new Page<>(page, limit);

        // 构造sql
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("code", code);
        wrapper.allEq(params, false); // 如果条件中参数为空时，则从条件中去除该参数


        Page<Product> productPage = null;
        List<ProductVo> productVos = null;
        try {
            // 执行分页查询
            productPage = mapper.selectPage(objectPage, wrapper);

            List<Product> products = new ArrayList<>(productPage.getRecords()); // 将分页列表数据转换为list

            // 拷贝到新实例对象，并且响应到前端
            productVos = new ArrayList<>();
            for (Product product : products) {
                ProductVo newProductVo = new ProductVo();
                BeanUtils.copyProperties(product, newProductVo); // 实例对象拷贝，更改属性名与前端对应
                productVos.add(newProductVo);
            }

        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }

        if (productPage != null) {
            // 获取角色总数
            long count = productPage.getTotal();
            response.put("count", count);
            response.put("data", productVos);
            response.put("success", true);
        } else {
            response.put("success", false);
            response.put("msg", "服务器异常！");
        }
        return response;
    }

    /**
     * 获取 application/x-www-form-urlencoded （表单）格式数据
     * @param id
     * @param name
     * @param code
     * @param inventory
     * @param storeHouse
     * @param site
     * @param type
     * @param token
     * @return
     */
    /*@PostMapping("/save")
    @ApiOperation(value = "库存管理-保存（添加编辑）")
    public Map<String, Object> productSave(@RequestParam(value = "id", required = false) Long id,
                                           @RequestParam(value = "name") String name,
                                           @RequestParam(value = "code") String code,
                                           @RequestParam(value = "inventory") Integer inventory,
                                           @RequestParam(value = "storeHouse") String storeHouse,
                                           @RequestParam(value = "site") String site,
                                           @RequestParam(value = "type") String type,
                                           @RequestParam(value = "token") String token) {

        // 获取当前登录用户
        String username = JwtUtil.extractUsername(token);

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        // 创建字符串 location 获取 （库房地址多个存储用 ，号隔开如： 库房，位置，位置编号） = location
        String location = storeHouse + "," + site;

        // 设置对象属性
        Product product = new Product();
        product.setId(id);
        product.setName(name);
        product.setCode(code);
        product.setInventory(inventory);
        product.setLocation(location);
        product.setType(type);
        if (id != null){
            product.setUpdateUser(username); // 有id表示更新操作
        }else {
            product.setCreateUser(username); // 无id表示保存操作
        }

        // 保存或更新方法
        boolean ret = false;
        try {
            if (product.getId() != null) {
                // 有id表示更新操作
                ret = service.updateById(product);
            } else {
                // 无id表示保存操作
                ret = service.save(product);
            }
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }

        if (ret) {
            response.put("success", true);
        } else {
            response.put("msg", "服务器异常！");
        }
        return response;
    }*/

    /**
     * 保存或更新操作-获取 application/json 格式数据
     *
     * @param dto
     * @return
     */
    @PostMapping("/save")
    @ApiOperation(value = "库存管理-保存（添加编辑）")
    public Map<String, Object> productSave(@RequestBody ProductDto dto) {

        // 获取当前登录用户
        String username = JwtUtil.extractUsername(dto.getToken());

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        // 设置对象属性
        Product product = Product.builder().id(dto.getId()).name(dto.getName()).code(dto.getCode()).inventory(dto.getInventory())
                .location(dto.getStoreHouse() + "," + dto.getSite()).type(dto.getType()).build();

        if (dto.getId() != null) {
            product.setUpdateUser(username); // 有id表示更新操作
        } else {
            product.setCreateUser(username); // 无id表示保存操作
        }

        // 保存或更新方法
        boolean ret = false;
        try {
            if (dto.getId() != null) {
                // 有id表示更新操作
                ret = service.updateById(product);
            } else {
                // 无id表示保存操作
                ret = service.save(product);
            }
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }

        if (ret) {
            response.put("success", true);
        } else {
            response.put("msg", "服务器异常！");
        }
        return response;

    }


    @DeleteMapping("/delete")
    @ApiOperation(value = "库存管理-删除产品")
    public Map<String, Object> productDelete(@RequestParam(value = "ids") Long id) {

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        try {
            boolean ret = service.removeById(id);
            if (ret) {
                response.put("success", true);
            } else {
                response.put("msg", "服务器异常");
            }
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }
        return response;
    }


    @PostMapping("/alarm/save")
    @ApiOperation(value = "库存管理-设置告警")
    public Map<String, Object> alarmSave(@RequestBody ProductAlarmDto alarmDto) {

        // 设置告警状态（如果告警限制数量大于等于库存数量时，发生告警）
        Integer alarm = alarmDto.getAlarmValue() >= alarmDto.getInventory() ? Const.ALARM : Const.UN_ALARM;

        int ret = 0;
        try {
            ret = mapper.update(alarmDto.getId(), alarmDto.getAlarmValue(), alarm);
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "业务处理异常，请稍后再试！");
        }

        Map<String, Object> response = new HashMap<>();
        if (ret > 0) {
            response.put("success", true);
        } else {
            response.put("msg", "服务器异常");
        }
        return response;
    }
}
